<?php defined('BASEPATH') OR exit('No direct script access allowed');

if ( ! function_exists('load_options'))
{
	/**
	 * Load options from option table
	 *
	 * @param $table : option table
	 * @param $value_column : field name to extract value
	 * @param $id_column : field name to extract id
	 * @param $where : where condition
	 * @return array of (id => value)
	 */
	function load_options($table, $value_column, $id_column, $where = NULL,$join = NULL)
	{
		$ci = & get_instance();
		$ci->db->select($id_column.','.$value_column);
		if (!empty($where))
			$ci->db->where($where);
        if(!empty($join['table']) && !empty($join['cond']) && !empty($join['pos']))
   			$ci->db->join($join['table'],$join['cond'],$join['pos']);
  		else if(!empty($join['table']) && !empty($join['cond']))
    		$ci->db->join($join['table'],$join['cond']);
		if ($ci->db->field_exists($table.'_order',$table))
			$ci->db->order_by($table.'_order','DESC');
        if ($ci->db->field_exists('ordering',$table))
			$ci->db->order_by('ordering','ASC');
		if($ci->db->field_exists($table.'_name',$table)){
			$ci->db->order_by($table.'_name',"ASC");
		}
		$items = $ci->db->get($table)->result_array();
		$tmp = array();
		if(!empty($join)){

			$value_column  = explode(".",$value_column);
			$value_column  = $value_column[1];
			$id_column     = explode(".",$id_column);
			$id_column 	   = $id_column[1];
		}
		foreach ($items as $item){
			$tmp[$item[$id_column]] = $item[$value_column];
		}
		return $tmp;
	}
	function get_color(){
		$ci = & get_instance();
		$data = $ci->db->get("color")->result_array();
		$list = "";
		foreach($data as $item){
			$list["filter"][$item["id"]] = $item["color-code"];	
			$list["name"][$item["id"]] = $item["color_name"];	
		}
		return $list;
	}
	function save_options($selected=array()){
		if (count($selected) > 1){
			$selected_str = implode("','",$selected);
			return  "'".$selected_str."'";
		} else{
			foreach($selected as $index => $value){
				return "'".$value."'";
			}
		}
	}
	function fetch_arr_options($str){
		$arr = array();
		if (!empty($str)){
			$arr =  explode("','",trim($str,"'"));
		} 
		return $arr;
	}
	function fetch_arr_options2($str){
		$arr = array();
		$arr2 = array();
		if (!empty($str)){
			$arr =  explode("','",trim($str,"'"));
		} 
		foreach($arr as $index =>$val){
			$arr2[$val] = $val;	
		}
		return $arr2;
	}
	function set_check_option($id,$str){
		$arr = fetch_arr_options($str);
		if (in_array($id, $arr)) return TRUE;
		else return FALSE;
	}
	function generateRandomString($length = 10) {
		$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$charactersLength = strlen($characters);
		$randomString = '';
		for ($i = 0; $i < $length; $i++) {
			$randomString .= $characters[rand(0, $charactersLength - 1)];
		}
		return $randomString;
	}
}